package com.gdufe.firesafe.service.impl;

import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.gdufe.firesafe.dao.NoticeDao;
import com.gdufe.firesafe.model.entity.NoticeEntity;
import com.gdufe.firesafe.exception.RRException;
import com.gdufe.firesafe.service.NoticeService;
import com.gdufe.firesafe.utils.PageUtils;
import com.gdufe.firesafe.utils.Query;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.Map;

@Service("noticeService")
public class NoticeServiceImpl extends ServiceImpl<NoticeDao, NoticeEntity> implements NoticeService {

    @Override
    public PageUtils queryPage(Map<String, Object> params) {
        String key = (String) params.get("key");
        QueryWrapper<NoticeEntity> queryWrapper = new QueryWrapper<>();
        if(key!=null) {
            queryWrapper.eq("id", key).or().like("title", key).or()
                    .like("content", key).or().like("publish_date", key)
                    .or().like("type", key).or().like("level", key)
                    .or().like("target", key);
        }
        IPage<NoticeEntity> page = this.page(
                new Query<NoticeEntity>().getPage(params),
                queryWrapper
        );

        return new PageUtils(page);
    }

    @Override
    public boolean save(NoticeEntity entity) {
        // 标题不能为空
        if(StrUtil.isBlank(entity.getTitle())){
            throw new RRException("标题不能为空");
        }
        entity.setPublishDate(new Date());
        return super.save(entity);
    }

}
